package drds.configuration.db.table_mapping;

import drds.configuration.common.Constants;
import drds.configuration.db.datasource.DataSourceContext;
import drds.configuration.db.datasource.DataSourceIdToDataSourceConfigMapContext;
import drds.tools.ClassSearcher;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 基于动态map的形式进行操作数据库
 */
@Slf4j
public class TableMapping {
    /**
     * 根据所有表名建立字段对应信息
     */
    // 选择性设置

    /**
     * 使用注解进行设置表信息
     */
    @SuppressWarnings("unchecked")
    public boolean buildAllModelAndTableInfoMapping(String basePackage) {
        if (Constants.devMode) {
            for (Map.Entry<String, DataSourceContext> entry : DataSourceIdToDataSourceConfigMapContext.dataSourceIdToDataSourceConfigMap.entrySet()) {
                log.debug("Key = " + entry.getKey() + ", Value = " + entry.getValue());
            }
        }
        try {
            List<Class> modelClassList = ClassSearcher.findSubClass(Model.class, basePackage);

            for (Class<Model<Model<?>>> modelClass : modelClassList) {
                Table table = modelClass.getAnnotation(Table.class);
                String groupDataSourceId;
                String tableName;
                if (table != null) {
                    // 如果含有注解则自动按照注解的形式配置--建议全部由注解配置[明确表名正确与否]
                    groupDataSourceId = table.groupDataSourceId();
                    tableName = table.tableName();
                    if (Constants.devMode) {
                        log.info("当前对表进行解析:groupDataSourceId" + groupDataSourceId + ",tableName:" + tableName);
                    }
                    if (groupDataSourceId == null || (groupDataSourceId != null && "".equals(groupDataSourceId))) {
                        log.error("Model Class注解上没有groupDataSourceId" + modelClass.getName());
                        throw new RuntimeException("Model Class注解上没有groupDataSourceId");
                    }
                    if (tableName == null || (tableName != null && "".equals(tableName))) {
                        log.error("Model Class注解上没有表名" + modelClass.getName());
                        throw new RuntimeException("Model Class注解上没有表名");
                    }
                    log.info("当前groupDataSourceId:" + groupDataSourceId);
                    DataSource masterDataSource = DataSourceIdToDataSourceConfigMapContext.dataSourceIdToDataSourceConfigMap.get(groupDataSourceId).getDataSource();
                    //
                    String primaryKey = table.primaryKey();
                    if (primaryKey == null || (primaryKey != null && "".equals(primaryKey))) {
                        addMapping(groupDataSourceId, masterDataSource, table, modelClass, tableName);// 默认是ID
                        log.debug("addMapping(表名:" + tableName + ", 主键:id,模型类名:" + modelClass.getName() + ")");
                    } else {
                        addMapping(groupDataSourceId, masterDataSource, table, modelClass, tableName, primaryKey);
                        log.debug("addMapping(表名:" + tableName + ", 主键:" + table.primaryKey() + ",模型类名:" + modelClass.getName() + ")");
                    }

                }
            }
            TableInfoBuilder.buildModelClassToTableInfoMap();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
        return true;
    }

    /**
     * 不含有主键
     */
    public TableMapping addMapping(String groupDataSourceId, DataSource masterDataSource, Table table, Class<? extends Model<?>> modelClass, String tableName) {
        TableInfo tableInfo = new TableInfo(groupDataSourceId, masterDataSource, tableName, modelClass);
        if (TableInfo.TRUE.equals(table.checkBaseColumn())) {
            tableInfo.setCheckBaseColumn(true);
        }
        //
        List<TableInfo> tableInfoList = DataSourceIdToDataSourceConfigMapContext.getDataSourceIdToTableInfoListMap().get(groupDataSourceId);
        if (tableInfoList == null) {
            tableInfoList = new ArrayList<TableInfo>();
        }
        tableInfoList.add(tableInfo);
        DataSourceIdToDataSourceConfigMapContext.getDataSourceIdToTableInfoListMap().put(groupDataSourceId, tableInfoList);
        //
        return this;
    }

    /**
     * 含有主键
     */
    public TableMapping addMapping(String groupDataSourceId, DataSource masterDataSource, Table table, Class<? extends Model<?>> modelClass, String tableName, String primaryKey) {
        TableInfo tableInfo = new TableInfo(groupDataSourceId, masterDataSource, tableName, primaryKey, modelClass);
        if (TableInfo.TRUE.equals(table.checkBaseColumn())) {
            tableInfo.setCheckBaseColumn(true);
        }
        //
        List<TableInfo> tableInfoList = DataSourceIdToDataSourceConfigMapContext.getDataSourceIdToTableInfoListMap().get(groupDataSourceId);
        if (tableInfoList == null) {
            tableInfoList = new ArrayList<TableInfo>();
        }
        tableInfoList.add(tableInfo);
        DataSourceIdToDataSourceConfigMapContext.getDataSourceIdToTableInfoListMap().put(groupDataSourceId, tableInfoList);
        return this;
    }


}
